// import React from 'react'
import {loadCartAPI,delFromCartAPI} from '../services/cart'
import { useState, useEffect } from 'react'; 
import { dalImg } from '../utils/tools';
import { Card,Button,Checkbox } from 'antd-mobile';

function Cart() { 
  const [list, setCartList] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]); // 存储选中的商品 ID
  const cartData =async()=>{
   const res = await loadCartAPI()
   setCartList(res.data.list);
  //  console.log(res.data.list);
  }
  
  useEffect(()=>{
    cartData()
   },[])

  // 处理复选框点击事件
  const handleCheckboxChange = (id) => {
    const index = selectedItems.indexOf(id);
    if (index > -1) {
      // 如果已经选中，则从数组中删除该商品 ID
      setSelectedItems(selectedItems.filter(itemId => itemId !== id));
    } else {
      // 如果未选中，则将该商品 ID 添加到数组中
      setSelectedItems([...selectedItems, id]);
    }
  }
  
  // 处理删除按钮点击事件
  const handleDelete = async () => {
    // 遍历选中的商品 ID，发送请求删除对应的商品
    for (const itemId of selectedItems) {
      await delFromCartAPI(itemId);
    }
    // 重新加载购物车数据
    cartData();
    // 清空选中的商品 ID 数组
    setSelectedItems([]);
  }

  return ( 
  <div style={{backgroundColor:'#cdddec'}}> 
      <div > 
      <h2 style={{textAlign:'center'}}>我的购物车</h2> 
        {list.map((item) => ( 
          <Checkbox key={item.id} 
          checked={selectedItems.indexOf(item.id) > -1}
          onChange={() => handleCheckboxChange(item.id)}
          >
          <Card  key={item.id} style={{display:'flex',border:'2px pink solid',width:"310px",height:'100px'}}  >
            <img style={{width:"60px",height:'60px',marginLeft:'10px'}} src={dalImg(item.medicine.image) } alt="" />
            <span style={{margin:'0 20px',fontSize:'20px',}}>{item.medicine.name}</span> 
            <span style={{fontSize:'20px'}}>{item.price}</span> 
           </Card>
           </Checkbox>
        ))} 
        {/* <Button>总价：</Button> */}
        <Button 
        style={{position:'sticky',top :'10px',left:'270px',backgroundColor:'pink'}}
        onClick={handleDelete}
        >删除</Button>
      </div> 
    </div> 
  ); 
} 

export default Cart





